package com.graduate.common.cookieUtil;

import com.graduate.bssp.entity.User;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by yongqiangyao on 2018/3/5.
 */
public class Util {
    public static void addCookie(User userInfo, HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
        if (userInfo!=null) {
            //创建cookie
            Cookie userIdCookie = new Cookie("userIdCookie", URLEncoder.encode(userInfo.getUserid().toString(), "utf-8"));
            Cookie nameCookie = new Cookie("UserName", URLEncoder.encode(userInfo.getName(), "utf-8"));
            Cookie passwordCookie = new Cookie("UserPassword", URLEncoder.encode(userInfo.getPassword(), "utf-8"));
            //设置cookie保存的时间 单位：秒 一天
            nameCookie.setMaxAge(24 * 60 * 60*7);
            nameCookie.setPath("/");
            passwordCookie.setPath("/");
            userIdCookie.setPath("/");
            //将cookie添加到响应
            response.addCookie(nameCookie);
            response.addCookie(passwordCookie);
            response.addCookie(userIdCookie);
        }
    }
    public static void clearCookie(HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
            //创建cookie
            Cookie userIdCookie = new Cookie("userIdCookie", URLEncoder.encode(""));
            Cookie nameCookie = new Cookie("UserName", URLEncoder.encode(""));
            Cookie passwordCookie = new Cookie("UserPassword", URLEncoder.encode(""));
            //设置cookie保存的时间 单位：秒 一天
            nameCookie.setMaxAge(24 * 60 * 60);
            nameCookie.setPath("/");
            passwordCookie.setPath("/");
            userIdCookie.setPath("/");
            //将cookie添加到响应
            response.addCookie(nameCookie);
            response.addCookie(passwordCookie);
            response.addCookie(userIdCookie);
    }
}
